package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.concurrent.TimeUnit;

/**
 * @author zzb
 * @create 2021/2/21
 */
@Service
@Transactional
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //文章审核
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }

    //文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }

    //根据id查询文章
    public void findById(String articleId) {
        //根据id从redis中查询文章如果找不到就从数据库找
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        //从数据库找
        if (article == null){
            Article article1 = articleDao.findById(articleId).get();
            //将文章放到redis中
            //参数一key参数二值
            //参数三到期时间
            redisTemplate.opsForValue().set("article_"+articleId,article1,10, TimeUnit.HOURS);
        }
    }

    //添加文章
    public void add(Article article) {
        //添加前清空redis中的文章
        redisTemplate.delete("article_"+article.getId());
        //保存
        articleDao.save(article);
    }
}
